package com.bookstore.web.servlet;

import com.bookstore.exception.UserException;
import com.bookstore.model.User;
import com.bookstore.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@WebServlet(urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);

        //校验验证码
        String client_code = req.getParameter("client_code");
        System.out.println("client_code:"+client_code);
        String session_code = (String) req.getSession().getAttribute("checkcode_session");
        System.out.println("session_code "+session_code);
        if(!session_code.equals(client_code)){
            req.setAttribute("code_err","验证码错误，请验证后提交！");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            //跳回注册页面
            return;
        }
//        req.setCharacterEncoding("UTF-8"); //处理乱码问题
        //1.将参数转成Bean
        //2、注册
        //3.返回成功，进入成功页面；失败，回到注册页面
        User user = new User();
        try {
            BeanUtils.populate(user, req.getParameterMap());
//            System.out.println(user);
            user.setActiveCode(UUID.randomUUID().toString()); //生成16位随机数字
            user.setRole("普通用户");
            user.setRegistTime(new Date());
//            System.out.println(user);
            UserService us = new UserService();
            us.register(user);
            req.getRequestDispatcher("registersuccess.jsp").forward(req,resp);

        } catch (UserException e) {
            e.printStackTrace();
            req.setAttribute("register_err",e.getMessage());
            req.getRequestDispatcher("register.jsp").forward(req,resp);


        } catch (Exception e) {
            System.out.println("注册失败");
            e.printStackTrace();
        }


    }
}
